package com.xiaochong.tir.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.api.component.CnyToUsdRateComponent;
import com.xiaochong.tir.api.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.api.component.RedisCacheComponent;
import com.xiaochong.tir.api.util.*;
import com.xiaochong.tir.common.data.hbasepo.TradesHistory;
import com.xiaochong.tir.common.data.mapper.*;
import com.xiaochong.tir.common.data.mapperSearchResult.ExchangeTransactionpair;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.data.vo.*;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by org on 2018/6/27.
 */
@Service("kLineTradesService")
public class KLineTradesService {
    @Autowired
    private RedisServer rediscConfig ;
    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;
    @Resource
    private CnyToUsdRateComponent cnyToUsdRateComponent;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private KLineTitleMapper kLineTitleMapper;
    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;
    @Autowired
    private ImmortalsService immortalsService;
    @Autowired
    private ExchangeInfoMapper exchangeInfoMapper;
    @Autowired
    private RedisCacheComponent redisCacheComponent;
    @Autowired
    private ShelSelectService shelSelectService;
    @Autowired
    private SelfSelectedMapper selfSelectedMapper;
    /**
     * 获取历史交易大单
     * @param number
     * @param exchangeId
     * @param symbol
     * @return
     */
    public ApiResultVo<List<ApiMaxTradesVo>> historyTradesMax(Integer number, Integer exchangeId, String symbol) {
        ApiResultVo<List<ApiMaxTradesVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<ApiMaxTradesVo> vo = new LinkedList<>();
        resultVo.setData(vo);
        if(null == number || null == exchangeId || StringUtils.isBlank(symbol)){//PARAMS_ERROR
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        try {
            List<PurchaseOrder> pList = purchaseOrderMapper.selectByEchangeAndSymbol(exchangeId,symbol,number);
            //获取汇率
            String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
            if(StringUtils.isBlank(rmbUsd)){
                rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
            }
            BigDecimal rmbCny = new BigDecimal(rmbUsd);
            //计算返回实体
            ApiMaxTradesVo maxTradesVo;
            if(pList != null && pList.size() > 0){
                for(PurchaseOrder po : pList){
                    BigDecimal price = new BigDecimal(po.getPrice());
                    BigDecimal amount = new BigDecimal(po.getCount());
                    maxTradesVo = new ApiMaxTradesVo();
                    maxTradesVo.setTimestamp(po.getTimeStamp());
                    maxTradesVo.setAmount(amount.setScale(2, BigDecimal.ROUND_DOWN).toString());
                    maxTradesVo.setAmountPrice(amount.multiply(price).multiply(rmbCny).setScale(2,BigDecimal.ROUND_DOWN).toString());
                    maxTradesVo.setPrice( getConverCut(price.multiply(rmbCny)));
                    maxTradesVo.setDeal_sign(po.getDealSign());
                    vo.add(maxTradesVo);
                }
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
        }catch (Exception e){
            LogTrace.error("k线-成交大单监控",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return  resultVo;
    }

    public ApiResultVo<ApiCapitalInflowSituationDataVo> capitalInflowSituation(Integer exchangeId, String symbol,String timePartType) {
        Long st = System.currentTimeMillis();
        ApiResultVo<ApiCapitalInflowSituationDataVo> resultVo = new ApiResultVo<>();
        ApiCapitalInflowSituationDataVo dataVo = new ApiCapitalInflowSituationDataVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<ApiCapitalInflowSituationVo> vo = new LinkedList<>();
        dataVo.setCapitalInflowSituation(vo);
        resultVo.setData(dataVo);
        //判断参数是否正常
        if(null == exchangeId || StringUtils.isBlank(symbol) || StringUtils.isBlank(timePartType)){//PARAMS_ERROR
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        //判断参数是否正常
        if(!"3h".equals(timePartType) && !"1d".equals(timePartType)){//PARAMS_ERROR
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        //图标数据
        ChartVo chartVo = new ChartVo();
        List<String> x = new ArrayList<>();
        List<String> y = new ArrayList<>();
        try {
            //1d 3h
            String data = "";
            if("3h".equals(timePartType)){
                String redisKey3hData= RedisKeysUtils.API_SERVICE_TRADES_3H_DATA+"@"+exchangeId+"@"+symbol;
                data = rediscConfig.get(redisKey3hData);
            }else if("1d".equals(timePartType)){
                String redisKey1dData= RedisKeysUtils.API_SERVICE_TRADES_1D_DATA+"@"+exchangeId+"@"+symbol;
                data = rediscConfig.get(redisKey1dData);
            }
            if(StringUtils.isNotBlank(data)){
                JSONObject jsonObjectChart = JSON.parseObject(data);
                x = JSON.parseArray(JSON.toJSONString(jsonObjectChart.get("x")),String.class);
                y = JSON.parseArray(JSON.toJSONString(jsonObjectChart.get("y")),String.class);
            }
            String redisKey24HCapitalFlow= RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+exchangeId+"@"+symbol;
            String redisData = rediscConfig.get(redisKey24HCapitalFlow);
            Map<String,ApiCapitalInflowSituationVo> allMap = new HashMap<>();
            JSONObject jsonObject = new JSONObject();
            if(StringUtils.isNotBlank(redisData)){
                jsonObject =  JSON.parseObject(redisData);
            }
            ApiCapitalInflowSituationVo today = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo fiveMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo tenMinutes = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo oneHours = new ApiCapitalInflowSituationVo();
            ApiCapitalInflowSituationVo dayHours = new ApiCapitalInflowSituationVo();
            if(null != jsonObject){
                today = JSON.parseObject(JSON.toJSONString(jsonObject.get("today")),ApiCapitalInflowSituationVo.class);
                fiveMinutes = JSON.parseObject(JSON.toJSONString(jsonObject.get("fiveMinutes")),ApiCapitalInflowSituationVo.class);
                tenMinutes = JSON.parseObject(JSON.toJSONString(jsonObject.get("tenMinutes")),ApiCapitalInflowSituationVo.class);
                oneHours = JSON.parseObject(JSON.toJSONString(jsonObject.get("oneHours")),ApiCapitalInflowSituationVo.class);
                dayHours = JSON.parseObject(JSON.toJSONString(jsonObject.get("dayHours")),ApiCapitalInflowSituationVo.class);
            }
            chartVo.setX(x);
            chartVo.setY(y);
            dataVo.setChartVo(chartVo);
            vo.add(today);
            vo.add(fiveMinutes);
            vo.add(tenMinutes);
            vo.add(oneHours);
            vo.add(dayHours);
            if(today != null && today.getBuySellAmount() != null){
                dataVo.setTodayCapitalInflow(today.getBuySellAmount());
            }
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            LogTrace.info("k线-5、10、1h资金流入","耗时",String.valueOf(System.currentTimeMillis()-st));
        }catch (Exception e){
            LogTrace.error("k线-5、10、1h资金流入",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        /*Collections.reverse(x);
        Collections.reverse(y);*/
        return resultVo;
    }
    public LocalDateTime getNowLocalDateTime(int exchangeId,String symbol){
        //从redis获取最后一条时间戳，如果没有去服务时间，最后去hbase获取对应条数数据
        String redisData = rediscConfig.get(RedisKeysUtils.API_SERVICE_TRADES+"@"+exchangeId+"@"+symbol);
        Long lastTimestamp = Long.MIN_VALUE;
        //获取redis中最大时间戳，后面去重使用
        if(StringUtils.isNotBlank(redisData)){
            List<TradesHistory> tradesRedisList = JSON.parseArray(redisData,TradesHistory.class);
            if(tradesRedisList != null && tradesRedisList.size() > 0){
                lastTimestamp = tradesRedisList.get(tradesRedisList.size()-1).getTimestamp();
            }
        }
        if(lastTimestamp == Long.MIN_VALUE){ //获取服务器当前时间
            lastTimestamp = System.currentTimeMillis();
        }
        LocalDateTime time = DateUtils.getDateTimeOfTimestamp(lastTimestamp);
        return time;
    }

    /**
     * 获取自定义栏目
     * @return
     */
    public ApiResultVo<List<ApiKLineTitleVo>> kActionQuantizationAllTitle() {
        Long st = System.currentTimeMillis();
        ApiResultVo<List<ApiKLineTitleVo>> resultVo = new ApiResultVo<>();
        List<ApiKLineTitleVo> dataVo = new ArrayList<>();
        resultVo.setData(dataVo);
        ApiKLineTitleVo vo;
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            KLineTitle title = new KLineTitle();
            title.setIsEnable(true);
            List<KLineTitle> titleList = kLineTitleMapper.selectByEntityList(title);
            if(null != titleList && titleList.size() > 0){
                for(KLineTitle kLineTitle:titleList){
                    vo = new ApiKLineTitleVo();
                    vo.setDefault(kLineTitle.getIsDefault());
                    vo.setTitleName(kLineTitle.getTitleName());
                    dataVo.add(vo);
                }
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
        }catch (Exception e){
            LogTrace.error("获取自定义栏目",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return resultVo;
    }

    /**
     * 行情k线
     * @param kActionQuantizationParamsVo
     * @return
     */
    public ApiResultVo<List<ApiKActionQuantizationVo>> kActionQuantization(kActionQuantizationParamsVo kActionQuantizationParamsVo) {
        Long st = System.currentTimeMillis();
        ApiResultVo<List<ApiKActionQuantizationVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(null == kActionQuantizationParamsVo.getShowType()){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        if(kActionQuantizationParamsVo.getShowType().intValue() == 2){
            if(null == kActionQuantizationParamsVo.getExchangeId()){
                resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
                return resultVo;
            }
        }
        try {
            //如果是精选查出精选交易所id以及交易对名称，如果是交易所查询需要查出交易对名称
            /*ExchangeTransactionpairMiddle query = new ExchangeTransactionpairMiddle();
            if(kActionQuantizationParamsVo.getShowType().intValue() == 1){//精选
                query.setSelected(1);
            }else{
                query.setExchangeId(kActionQuantizationParamsVo.getExchangeId());
            }
            List<ApiKActionQuantizationVo> dataVo = this.getKLineQuantizationExchange(query);
            */
            String redisKey = RedisKeysUtils.API_SERVICE_TRADES_EXCHANGE_SELECT_ALL_DATA+"@";
            //放入不同的redis中
            if(kActionQuantizationParamsVo.getShowType().intValue()  == 1){//精选
                redisKey +="select@0";
            }else{
                redisKey +="exchange@"+kActionQuantizationParamsVo.getExchangeId();
            }
            String data = rediscConfig.get(redisKey);
            List<ApiKActionQuantizationVo> dataVo = new ArrayList<>();
            if(StringUtils.isNotBlank(data)){
                dataVo = JSON.parseArray(data,ApiKActionQuantizationVo.class);
            }
            if(dataVo == null || dataVo.size() == 0){
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            //排序--根据排序取出对应的条数对应的页数的数据返回前端
            if(StringUtils.isBlank(kActionQuantizationParamsVo.getSortField())){//设置默认排序字段是当前价格
                kActionQuantizationParamsVo.setSortField("amount");
            }
            if(StringUtils.isBlank(kActionQuantizationParamsVo.getSortType())){//设置默认排序为降序
                kActionQuantizationParamsVo.setSortType("desc");
            }
            ListSortUtil util=new ListSortUtil();
            util.mySort( dataVo, kActionQuantizationParamsVo.getSortField().trim(), kActionQuantizationParamsVo.getSortType().trim() );
            //排名
            if (dataVo.size()>0){
                for (int i=0;i<dataVo.size();i++){
                    dataVo.get( i ).setRank( i+1 );
                }
            }
            //插入分页默认值分页
            if(kActionQuantizationParamsVo.getPageIndex()==null){
                kActionQuantizationParamsVo.setPageIndex( 1 );
            }
            if(kActionQuantizationParamsVo.getPageSize()==null){
                kActionQuantizationParamsVo.setPageSize( 20 );
            }
            List<ApiKActionQuantizationVo> result= ListSortPageUtil.pageBean(dataVo,kActionQuantizationParamsVo.getPageIndex(),kActionQuantizationParamsVo.getPageSize());
            //判断每条数据是否已自选(如果用户已经登录)
            if(StringUtils.isNotBlank(kActionQuantizationParamsVo.getUserToken())){
                Integer user_id = shelSelectService.getRedisUserId(kActionQuantizationParamsVo.getUserToken());
                if(null != user_id){
                    List<Integer> middleList = new ArrayList<>();
                    for(ApiKActionQuantizationVo q:result){
                        middleList.add(q.getMiddleId());
                    }
                    if(middleList.size() > 0){
                        Map<String,Object> params = new HashMap<>();
                        params.put("type",1);
                        params.put("uniqueAnnotationList",middleList);
                        params.put("user_id",user_id);
                        List<SelfSelected> selfList = selfSelectedMapper.getSelfSelectByMideleId(params);
                        if(selfList != null && selfList.size()>0){
                            Map<Integer,Object> selfMap = new HashMap<>();
                            for(SelfSelected selfSelected : selfList){
                                selfMap.put(selfSelected.getUniqueAnnotation(),selfSelected.getUniqueAnnotation());
                            }
                            for(ApiKActionQuantizationVo q:result){
                                if(q.getMiddleId() != null && selfMap.containsKey(q.getMiddleId())){
                                    q.setSelfSelectFlag(1);
                                }
                            }
                        }
                    }
                }
            }
            //计算页数
            int pages = dataVo.size()/kActionQuantizationParamsVo.getPageSize();
            int yu = dataVo.size()%kActionQuantizationParamsVo.getPageSize();
            if(yu > 0){
                pages = pages+1;
            }
            resultVo.setData(result);
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            resultVo.setPages(pages);
            resultVo.setTotal(dataVo.size());
        }catch (Exception e){
            LogTrace.error("行情k线",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("行情k线api","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }
    public ApiResultVo<List<ApiKActionQuantizationVo>> kActionQuantizationSearchMarket(kActionQuantizationParamsVo kActionQuantizationParamsVo) {
        Long st = System.currentTimeMillis();
        ApiResultVo<List<ApiKActionQuantizationVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        String searchName = kActionQuantizationParamsVo.getSearchName();
        if(StringUtils.isBlank(searchName)){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        List<ApiKActionQuantizationVo> vo = new ArrayList<>();
        try {
            List<ApiKActionQuantizationVo> allData = new ArrayList<>();
            //查询交易所
            ExchangeInfo exchangeInfo=new ExchangeInfo();
            exchangeInfo.setEnableFlag( true );
            exchangeInfo.setDeleteFlag( false );
            exchangeInfo.setKlineStatus( true );
            List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
            String redisKeyCom = RedisKeysUtils.API_SERVICE_TRADES_EXCHANGE_SELECT_ALL_DATA+"@";
            String redisKeyExchange;
            String data;
            List<ApiKActionQuantizationVo> exchangeList;
            for(ExchangeInfo exchange : infoList){
                redisKeyExchange = redisKeyCom+"exchange@"+exchange.getId();
                data = rediscConfig.get(redisKeyExchange);
                if(StringUtils.isNotBlank(data)){
                    exchangeList = JSON.parseArray(data,ApiKActionQuantizationVo.class);
                    //查找所有数据放入allData中
                    if(exchangeList != null && exchangeList.size() > 0){
                        allData.addAll(exchangeList);
                    }
                }
            }
            String query = searchName.toUpperCase();
            //根据查询的字段模糊匹配放入vo中
            for(ApiKActionQuantizationVo quantization:allData){
                if(quantization.getTransactionName().startsWith(query)){
                    vo.add(quantization);
                }

            }

            if(vo == null || vo.size() == 0){
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            //排序--根据排序取出对应的条数对应的页数的数据返回前端
            if(StringUtils.isBlank(kActionQuantizationParamsVo.getSortField())){//设置默认排序字段是当前价格
                kActionQuantizationParamsVo.setSortField("lastOpenPrice");
            }
            if(StringUtils.isBlank(kActionQuantizationParamsVo.getSortType())){//设置默认排序为降序
                kActionQuantizationParamsVo.setSortType("desc");
            }
            ListSortUtil util=new ListSortUtil();
            util.mySort( vo, kActionQuantizationParamsVo.getSortField().trim(), kActionQuantizationParamsVo.getSortType().trim() );
            //排名
            if (vo.size()>0){
                for (int i=0;i<vo.size();i++){
                    vo.get( i ).setRank( i+1 );
                }
            }
            //插入分页默认值分页
            if(kActionQuantizationParamsVo.getPageIndex()==null){
                kActionQuantizationParamsVo.setPageIndex( 1 );
            }
            if(kActionQuantizationParamsVo.getPageSize()==null){
                kActionQuantizationParamsVo.setPageSize( 20 );
            }

            List<ApiKActionQuantizationVo> result= ListSortPageUtil.pageBean(vo,kActionQuantizationParamsVo.getPageIndex(),kActionQuantizationParamsVo.getPageSize());
            //判断每条数据是否已自选(如果用户已经登录)
            if(StringUtils.isNotBlank(kActionQuantizationParamsVo.getUserToken())){
                Integer user_id = shelSelectService.getRedisUserId(kActionQuantizationParamsVo.getUserToken());
                if(null != user_id){
                    List<Integer> middleList = new ArrayList<>();
                    for(ApiKActionQuantizationVo q:result){
                        middleList.add(q.getMiddleId());
                    }
                    if(middleList.size() > 0){
                        Map<String,Object> params = new HashMap<>();
                        params.put("type",1);
                        params.put("uniqueAnnotationList",middleList);
                        params.put("user_id",user_id);
                        List<SelfSelected> selfList = selfSelectedMapper.getSelfSelectByMideleId(params);
                        if(selfList != null && selfList.size()>0){
                            Map<Integer,Object> selfMap = new HashMap<>();
                            for(SelfSelected selfSelected : selfList){
                                selfMap.put(selfSelected.getUniqueAnnotation(),selfSelected.getUniqueAnnotation());
                            }
                            for(ApiKActionQuantizationVo q:result){
                                if(q.getMiddleId() != null && selfMap.containsKey(q.getMiddleId())){
                                    q.setSelfSelectFlag(1);
                                }
                            }
                        }
                    }
                }
            }
            //计算页数
            int pages = vo.size()/kActionQuantizationParamsVo.getPageSize();
            int yu = vo.size()%kActionQuantizationParamsVo.getPageSize();
            if(yu > 0){
                pages = pages+1;
            }
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            resultVo.setPages(pages);
            resultVo.setTotal(vo.size());
            resultVo.setData(result);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("k线行情-搜索交易对",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("k线行情-搜索交易对","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }
    /**
     * 选币查询
     * @param index
     * @return
     */
    public ApiResultVo<List<CurrencyQuotationResultVo>> SelectCoinQuantization(Integer index) {
        long st = System.currentTimeMillis();
        ApiResultVo<List<CurrencyQuotationResultVo>>  resultVo = new ApiResultVo<>();
        List<CurrencyQuotationResultVo> vo = new ArrayList<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(index == null){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        try {
            String redisKey = SelectCoinTypeEnum.getNameByIndex(index);
            //获取redis计算出来的货币
            String data = rediscConfig.get(redisKey);
            List<CurrencyExchangeTransaction> currencyInfoList = new ArrayList<>();
            if(StringUtils.isNotBlank(data)){
                currencyInfoList = JSON.parseArray(data,CurrencyExchangeTransaction.class);
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            CurrencyQuotationResultVo currencyQuotationResultVo;
            //循环查询货币行情
            if(currencyInfoList != null && currencyInfoList.size() > 0){
                for(CurrencyExchangeTransaction currencyInfo : currencyInfoList){
                    currencyQuotationResultVo=immortalsService.getCurrencyByCmcId( currencyInfo.getCmcId() );
                    if(currencyQuotationResultVo != null){
                        vo.add(currencyQuotationResultVo);
                    }
                }
            }
            resultVo.setData(vo);
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("选币获取货币行情",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("选币获取货币行情api","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }

    /**
     * 选币分页
     * @param selectCoinQuantizationParamsVo
     * @return
     */
    public ApiResultVo<List<CurrencyQuotationResultVo>> SelectCoinQuantizationPage(SelectCoinQuantizationParamsVo selectCoinQuantizationParamsVo) {
        long st = System.currentTimeMillis();
        ApiResultVo<List<CurrencyQuotationResultVo>>  resultVo = new ApiResultVo<>();
        List<CurrencyQuotationResultVo> vo = new ArrayList<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(selectCoinQuantizationParamsVo.getIndex() == null){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        try {
            String redisKey = SelectCoinTypeEnum.getNameByIndex(selectCoinQuantizationParamsVo.getIndex());
            //获取redis计算出来的货币
            String data = rediscConfig.get(redisKey);
            List<CurrencyExchangeTransaction> currencyInfoList = new ArrayList<>();
            if(StringUtils.isNotBlank(data)){
                currencyInfoList = JSON.parseArray(data,CurrencyExchangeTransaction.class);
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            CurrencyQuotationResultVo currencyQuotationResultVo;
            //循环查询货币行情
            if(currencyInfoList != null && currencyInfoList.size() > 0){
                for(CurrencyExchangeTransaction currencyInfo : currencyInfoList){
                    currencyQuotationResultVo=immortalsService.getCurrencyByCmcId( currencyInfo.getCmcId(),selectCoinQuantizationParamsVo.getUserToken());
                    if(currencyQuotationResultVo != null){
                        vo.add(currencyQuotationResultVo);
                    }
                }
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            //排序--根据排序取出对应的条数对应的页数的数据返回前端
            if(StringUtils.isBlank(selectCoinQuantizationParamsVo.getSortField())){//设置默认排序字段是当前价格
                selectCoinQuantizationParamsVo.setSortField("lastOpenPrice");
            }
            if(StringUtils.isBlank(selectCoinQuantizationParamsVo.getSortType())){//设置默认排序为降序
                selectCoinQuantizationParamsVo.setSortType("desc");
            }
            ListSortUtil util=new ListSortUtil();
            util.mySort( vo, selectCoinQuantizationParamsVo.getSortField().trim(), selectCoinQuantizationParamsVo.getSortType().trim() );
            //排名
            if (vo.size()>0){
                for (int i=0;i<vo.size();i++){
                    vo.get( i ).setRank( i+1 );
                }
            }
            //插入分页默认值分页
            if(selectCoinQuantizationParamsVo.getPageIndex()==null){
                selectCoinQuantizationParamsVo.setPageIndex( 1 );
            }
            if(selectCoinQuantizationParamsVo.getPageSize()==null){
                selectCoinQuantizationParamsVo.setPageSize( 20 );
            }

            List<CurrencyQuotationResultVo> result= ListSortPageUtil.pageBean(vo,selectCoinQuantizationParamsVo.getPageIndex(),selectCoinQuantizationParamsVo.getPageSize());
            //计算页数
            int pages = vo.size()/selectCoinQuantizationParamsVo.getPageSize();
            int yu = vo.size()%selectCoinQuantizationParamsVo.getPageSize();
            if(yu > 0){
                pages = pages+1;
            }
            resultVo.setPages(pages);
            resultVo.setTotal(vo.size());
            resultVo.setData(result);
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("选币获取货币行情分页",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("选币获取货币行情api分页","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }
    /**
     * 搜索交易对
     * @param searchName
     * @return
     */
    public ApiResultVo<List<ApiKActionQuantizationVo>> kActionQuantizationSearch(String searchName,String userToken) {
        Long st = System.currentTimeMillis();
        ApiResultVo<List<ApiKActionQuantizationVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(StringUtils.isBlank(searchName)){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        List<ApiKActionQuantizationVo> vo = new ArrayList<>();
        try {
            List<ApiKActionQuantizationVo> allData = new ArrayList<>();
            //查询交易所
            ExchangeInfo exchangeInfo=new ExchangeInfo();
            exchangeInfo.setEnableFlag( true );
            exchangeInfo.setDeleteFlag( false );
            exchangeInfo.setKlineStatus( true );
            List<ExchangeInfo> infoList=exchangeInfoMapper.selectByEntityList( exchangeInfo );
            String redisKeyCom = RedisKeysUtils.API_SERVICE_TRADES_EXCHANGE_SELECT_ALL_DATA+"@";
            String redisKeyExchange;
            String data;
            List<ApiKActionQuantizationVo> exchangeList;
            for(ExchangeInfo exchange : infoList){
                redisKeyExchange = redisKeyCom+"exchange@"+exchange.getId();
                data = rediscConfig.get(redisKeyExchange);
                if(StringUtils.isNotBlank(data)){
                    exchangeList = JSON.parseArray(data,ApiKActionQuantizationVo.class);
                    //查找所有数据放入allData中
                    if(exchangeList != null && exchangeList.size() > 0){
                        allData.addAll(exchangeList);
                    }
                }
            }
            String query = searchName.toUpperCase();
            //根据查询的字段模糊匹配放入vo中
            for(ApiKActionQuantizationVo quantization:allData){
                /*if(quantization.getTransactionName().indexOf(searchName) >=0){
                    vo.add(quantization);
                }*/
                if(quantization.getTransactionName().startsWith(query)){
                    //判断是否是自选
                   /* if(StringUtils.isNotBlank(userToken)){
                        Integer selfSelectFlag = shelSelectService.valicatSymbolSelfSelect(userToken,quantization.getMiddleId(),1);
                        quantization.setSelfSelectFlag(selfSelectFlag);
                    }*/
                    vo.add(quantization);
                }

            }
            if(vo.size() > 0){
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
            resultVo.setData(vo);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("k线行情-搜索交易对",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("k线行情-搜索交易对","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }

    public static BigDecimal getConverCut(String lastPriceB) {
        BigDecimal result = new BigDecimal(0);
        result = StringUtils.isNotBlank(lastPriceB)?new BigDecimal(lastPriceB).setScale(10,BigDecimal.ROUND_DOWN):result;
        if(result.compareTo(BigDecimal.valueOf(1)) >=0){
            result = result.setScale(2,BigDecimal.ROUND_DOWN);
        }else{
            BigDecimal divisor = BigDecimal.ONE;
            MathContext mc = new MathContext(5);
            result = result.divide(divisor, mc);
        }
        return result;
    }
    /**
     * 保存5位有效数据如果小于1
     * @param lastPriceB
     * @return
     */
    public static String getConverCut(BigDecimal lastPriceB) {
        //String result = "0";
        BigDecimal result = BigDecimal.ZERO;
        result = lastPriceB!=null?lastPriceB.setScale(10,BigDecimal.ROUND_DOWN):result;
        if(result.compareTo(BigDecimal.valueOf(1)) >=0){
            result = result.setScale(2,BigDecimal.ROUND_DOWN);
        }else{
            BigDecimal divisor = BigDecimal.ONE;
            MathContext mc = new MathContext(5);
            result = result.divide(divisor, mc);
        }
        return result.stripTrailingZeros().toPlainString();
    }
    public ApiResultVo validateSymbolSelfSelect(Integer middleId, String userToken) {
        Long st = System.currentTimeMillis();
        ApiResultVo resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        if(middleId == null){
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        LogTrace.infoKvs("k线行情-查询交易对是否自选","userToken",userToken,"middleId",middleId.toString());
        try {
            Map<String,Object> stringObjectMap = new  HashMap();
            if(!StringUtils.isBlank(userToken)){
                Integer selfSelectFlag = shelSelectService.valicatSymbolSelfSelect(userToken,middleId,1);
                stringObjectMap.put("selfSelectFlag",selfSelectFlag);
            }else{
                stringObjectMap.put("selfSelectFlag",2);
            }
            resultVo.setData(stringObjectMap);
            resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
            resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("k线行情-查询交易对是否自选",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        LogTrace.info("k线行情-k线行情-查询交易对是否自选","总耗时",String.valueOf(System.currentTimeMillis()- st));
        return resultVo;
    }
   /* *//**
     * 根据实体获取k线行情数据
     * @param query
     * @return
     *//*
    public List<ApiKActionQuantizationVo> getKLineQuantizationExchange(ExchangeTransactionpairMiddle query){
        long st = System.currentTimeMillis();
        List<ApiKActionQuantizationVo> dataVo = new ArrayList<>();
        //获取所有货币,组装每个需要诊断数据放到redis中
        List<ExchangeTransactionpair> middleList = exchangeTransactionpairMiddleMapper.selectByEntityListOfKLine(query);
        if(middleList == null || middleList.size() == 0){
            return null;
        }
        Integer queryExchange = query.getExchangeId()!=null?query.getExchangeId():0;
        KActionTotalPo kActionTotalPo;
        String data;
        LocalDateTime time = LocalDateTime.now();
        Map<String,ApiCapitalInflowSituationVo> flowMap;
        ApiCapitalInflowSituationVo today ;
        String redisKey;
        String redisPriceDate = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymds);
        ApiKActionQuantizationVo vo;
        //long ss = System.currentTimeMillis();
        BigDecimal lastPriceB = new BigDecimal(0);//最新价格人民币和今日开盘价格,y用于小数点截取两位小数
        BigDecimal buyM = BigDecimal.ZERO;
        BigDecimal sellM = BigDecimal.ZERO;
        //获取货币，转成map
        List<CurrencyInfo>  allCurrencyInfo = redisCacheComponent.getCurrencyList();
        Map<String,String> currencyInfoMap = new HashMap<>();
        if(allCurrencyInfo != null && allCurrencyInfo.size() > 0){
            for(CurrencyInfo currencyInfo:allCurrencyInfo){
                currencyInfoMap.put(currencyInfo.getCmcId(),currencyInfo.getImageUrl());
            }
        }
        String cmcId = "";
        // 组装数据
        for(ExchangeTransactionpair pair:middleList){
            vo = new ApiKActionQuantizationVo();
            kActionTotalPo = new KActionTotalPo();
            //获取24h涨幅、今日涨幅、1h涨幅、最新价格,今日开盘
            //ss = System.currentTimeMillis();
            redisKey = RedisKeysUtils.API_SERVICE_K_ACTION_CHANGE_PRICE+"@"+pair.getExchangeId()+"@"+pair.getTransactionName()+"@"+redisPriceDate;
            data = rediscConfig.get(redisKey);
           // LogTrace.info("行情k线","获取最新价格数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            vo.setExchangeId(pair.getExchangeId());
            vo.setExchangeName(pair.getExchangeName());
            vo.setTransactionId(pair.getTransactionId());
            vo.setTransactionName(pair.getTransactionName());
            vo.setTimeLong(System.currentTimeMillis());
            cmcId = pair.getTransactionName().split("/")[0];
            vo.setImageUrl(currencyInfoMap.get(cmcId));
            //vo.setImageUrl(pair.getImageUrl());
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                vo.setChangePrice(StringUtils.isNotBlank(kActionTotalPo.getChangePrice())?Double.valueOf(kActionTotalPo.getChangePrice()):0);
                vo.setChangePrice1H(StringUtils.isNotBlank(kActionTotalPo.getChangePrice1H())?Double.valueOf(kActionTotalPo.getChangePrice1H()):0);
                vo.setChangePriceToday(StringUtils.isNotBlank(kActionTotalPo.getChangePriceToday())?Double.valueOf(kActionTotalPo.getChangePriceToday()):0);
                vo.setChangFlag(kActionTotalPo.getChangFlag()!=null?kActionTotalPo.getChangFlag():0);
                lastPriceB = this.getConverCut(kActionTotalPo.getOpenPriceCny());
                vo.setLastOpenPrice(Double.valueOf(lastPriceB.toString()));
                lastPriceB = this.getConverCut(kActionTotalPo.getTodayOpenPriceCny());
                vo.setOpenPriceCny(Double.valueOf(lastPriceB.toString()));
            }
            //获取24h最高、最低价格、昨日收盘价格
            //ss = System.currentTimeMillis();API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME
            redisKey = RedisKeysUtils.API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取24h交易量数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                lastPriceB = this.getConverCut(kActionTotalPo.getMaxPrice24H());
                vo.setMaxPrice24H(Double.valueOf(lastPriceB.toString()));
               // vo.setMaxPrice24H(StringUtils.isNotBlank(kActionTotalPo.getMaxPrice24H())?Double.valueOf(kActionTotalPo.getMaxPrice24H()):0);
                lastPriceB = this.getConverCut(kActionTotalPo.getMinPrice24H());
                vo.setMinPrice24H(Double.valueOf(lastPriceB.toString()));
                //vo.setMinPrice24H(StringUtils.isNotBlank(kActionTotalPo.getMinPrice24H())?Double.valueOf(kActionTotalPo.getMinPrice24H()):0);
                //vo.setAmount(StringUtils.isNotBlank(kActionTotalPo.getAmount())?Double.valueOf(kActionTotalPo.getAmount()):0);
                if(null != kActionTotalPo && StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())){
                   // lastPriceB = StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())?new BigDecimal(kActionTotalPo.getYesterdayClosePriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    lastPriceB = this.getConverCut(kActionTotalPo.getYesterdayClosePriceCny());
                    vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                   // vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }
            //获取24小时净流入,24h成交额
            JSONObject jsonObject;
            //ss = System.currentTimeMillis();
            redisKey = RedisKeysUtils.API_SERVICE_TRADES_24H_CAPITAL_FLOW_DATA+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取24小时净流入数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                jsonObject = JSON.parseObject(data);
                //today = new ApiCapitalInflowSituationVo();
                //today = JSON.parseObject(JSON.toJSONString(jsonObject.get("today")),ApiCapitalInflowSituationVo.class);
               *//* if(today != null && StringUtils.isNotBlank(today.getBuySellAmount())){
                }*//*
                today = JSON.parseObject(JSON.toJSONString(jsonObject.get("dayHours")),ApiCapitalInflowSituationVo.class);
                if(today != null && StringUtils.isNotBlank(today.getBuyAmount()) && StringUtils.isNotBlank(today.getSellAmount())){
                    buyM = new BigDecimal(today.getBuyAmount());
                    sellM = new BigDecimal(today.getSellAmount());
                    buyM = buyM.add(sellM);
                    buyM = getConverCut(buyM.toString());
                    // double amount = Double.valueOf(buyM.toString());
                    vo.setAmount(Double.valueOf(buyM.toString()));
                    vo.setCapitionFlow(Double.valueOf(today.getBuySellAmount()));
                }
            }
            //获取今日开盘 --已经放入API_SERVICE_K_ACTION_CHANGE_PRICE redis中
            //ss = System.currentTimeMillis();
            *//*redisKey = RedisKeysUtils.API_SERVICE_TRADES_PRIOD+"@"+pair.getExchangeId()+"@"+pair.getTransactionName()+"@"+redisPriceDate;
            data = rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取今日开盘数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                TradesHistory tradesHistory = JSON.parseObject(data,TradesHistory.class);
                if(tradesHistory != null && null != tradesHistory.getPrice()){
                    lastPriceB = StringUtils.isNotBlank(tradesHistory.getPriceCny())?new BigDecimal(tradesHistory.getPriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    vo.setOpenPriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }*//*
            //获取昨日收盘 -- 放入24小时最高、最低、24小时成交量rdis中（API_SERVICE_TRADES_24H_MAX_MIN_PRICE_VOLUME）
            //ss = System.currentTimeMillis();
            *//*redisKey= RedisKeysUtils.API_SERVICE_TRADES_PRIOD_YESTERDAY+"@"+pair.getExchangeId()+"@"+pair.getTransactionName();
            data= rediscConfig.get(redisKey);
            //LogTrace.info("行情k线","获取昨日收盘数据耗时",String.valueOf(System.currentTimeMillis()- ss));
            if(StringUtils.isNotBlank(data)){
                kActionTotalPo =  JSON.parseObject(data,KActionTotalPo.class);
                if(null != kActionTotalPo && StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())){
                    lastPriceB = StringUtils.isNotBlank(kActionTotalPo.getYesterdayClosePriceCny())?new BigDecimal(kActionTotalPo.getYesterdayClosePriceCny()).setScale(2,BigDecimal.ROUND_DOWN):BigDecimal.valueOf(0);
                    vo.setYesterdayClosePriceCny(Double.valueOf(lastPriceB.toString()));
                }
            }*//*
            dataVo.add(vo);
        }
        LogTrace.info("行情k线-akka","获取所有数据耗时-"+queryExchange,String.valueOf(System.currentTimeMillis()- st));
        return dataVo;
    }*/









    /*public ApiResultVo<List<ApiMaxTradesVo>> historyTradesMax(Integer number, Integer exchangeId, String symbol) {
        ApiResultVo<List<ApiMaxTradesVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<ApiMaxTradesVo> vo = new LinkedList<>();
        resultVo.setData(vo);
        if(null == number || null == exchangeId || StringUtils.isBlank(symbol)){//PARAMS_ERROR
            resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
            return resultVo;
        }
        try {
            //从redis获取最后一条时间戳，如果没有去服务时间，最后去hbase获取对应条数数据
            String redisData = rediscConfig.get(RedisKeysUtils.API_SERVICE_TRADES+"@"+exchangeId+"@"+symbol);
            Long lastTimestamp = Long.MIN_VALUE;
            //获取redis中最大时间戳，后面去重使用
            if(StringUtils.isNotBlank(redisData)){
                List<TradesHistory> tradesRedisList = JSON.parseArray(redisData,TradesHistory.class);
                if(tradesRedisList != null && tradesRedisList.size() > 0){
                    lastTimestamp = tradesRedisList.get(tradesRedisList.size()-1).getTimestamp();
                }
            }
            if(lastTimestamp == Long.MIN_VALUE){ //获取服务器当前时间
                lastTimestamp = System.currentTimeMillis();
            }
            LocalDateTime time = DateUtils.getDateTimeOfTimestamp(lastTimestamp);
            String minutePart = "";
            int numbersearch =1;
            String rowKey ="";
            String hbaseData ="";
            List<TradesHistory> tempData ;
            List<TradesHistory> tradesList = new ArrayList<>();
            while (numbersearch <= number){
                minutePart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdhm);
                time = time.minusMinutes(1);
                rowKey = minutePart+"@"+exchangeId+"@"+symbol;
                System.out.println(rowKey);
                hbaseData = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME
                        , HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME_FAMILY
                        , HbaseTableUtils.API_SERVICE_TRADES_QUALIFIER
                        , rowKey);
                tempData = (List<TradesHistory>) JSON.parseArray(hbaseData,TradesHistory.class);
                if(tempData != null && tempData.size() > 0){
                    for(int i=tempData.size()-1;i>=0;i--){
                        TradesHistory tradesHistory = tempData.get(i);
                        tradesList.add(tradesHistory);
                        numbersearch++;
                        if(numbersearch > number){
                            break;
                        }
                    }
                }
            }
            //获取汇率
            String rmbUsd = rediscConfig.get(RedisKeysUtils.RMB_USD_RATE);
            if(StringUtils.isBlank(rmbUsd)){
                rmbUsd = cnyToUsdRateComponent.getCnyUsdRate();
            }
            BigDecimal rmbCny = new BigDecimal(rmbUsd);
            //计算返回实体
            ApiMaxTradesVo maxTradesVo;
            for(TradesHistory trades : tradesList){
                maxTradesVo = new ApiMaxTradesVo();
                maxTradesVo.setTimestamp(trades.getTimestamp().toString());
                maxTradesVo.setAmount(trades.getAmount().setScale(2, BigDecimal.ROUND_DOWN).toString());
                maxTradesVo.setAmountPrice(trades.getAmount().multiply(rmbCny).setScale(2,BigDecimal.ROUND_DOWN).toString());
                maxTradesVo.setPrice(trades.getPrice().multiply(rmbCny).setScale(2,BigDecimal.ROUND_DOWN).toString());
                vo.add(maxTradesVo);
            }
            Collections.reverse(vo);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
        }catch (Exception e){
            LogTrace.error("k线-成交大单监控",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return  resultVo;
    }*/
}
